package com.afd.ozblip.share;

import com.afd.ozblip.activity.BaseActivity;
import com.afd.ozblip.activity.R;
import com.afd.ozblip.util.AsyncAction;
import com.afd.ozblip.util.AsyncLoadData;
import com.afd.ozblip.util.StringUtil;
import com.tencent.weibo.oauthv2.OAuthV2;
import com.tencent.weibo.oauthv2.OAuthV2Client;
import com.weibo.net.AccessToken;
import com.weibo.net.Oauth2AccessTokenHeader;
import com.weibo.net.Token;
import com.weibo.net.Utility;
import com.weibo.net.Weibo;
import com.weibo.net.WeiboParameters;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.http.SslError;
import android.os.Bundle;
import android.view.View;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

public class WeiboOAuthActivity extends BaseActivity {

	private String mAuthUrl = null;
	private ProgressBar mProgressBar;
	private WebView webView;
	// 微博分享类型
	private String weiboType;

	// 腾讯微博变量
	public final static int RESULT_CODE = 2;
	private OAuthV2 oAuth;
	// 用户微博Id
	private String userWBId;

	public void onCreate(Bundle paramBundle) {
		super.onCreate(paramBundle);
		// 设置视图
		setContentView(R.layout.web_view);
		// 启动返回功能
		toBack();
		// 初始化参数
		initView();
		// 获取参数
		getParame();
		if (this.mAuthUrl != null) {
			initWebView(this.mAuthUrl);
		}
	}

	public void getParame() {
		Intent intent = getIntent();
		this.weiboType = intent.getStringExtra("weiboType");
		if (ShareConfig.SHARE_WEIBO_QQ.equals(weiboType)) {
			oAuth = (OAuthV2) intent.getExtras().getSerializable("oauth");
			this.mAuthUrl = OAuthV2Client.generateImplicitGrantUrl(oAuth);
		} else if (ShareConfig.SHARE_WEIBO_SINA.equals(weiboType)) {
			this.mAuthUrl = intent.getStringExtra("authUrl");
		}
	}

	public void initView() {
		this.mProgressBar = ((ProgressBar) findViewById(R.id.progressbar_loading));
	}

	private void initWebView(String paramString) {
		this.webView = (WebView) findViewById(R.id.webView);
		webView.clearCache(true);
		webView.getSettings().setJavaScriptEnabled(true);
		webView.getSettings().setSupportZoom(true);
		webView.getSettings().setBuiltInZoomControls(true);
		webView.setWebViewClient(new WebViewC());
		webView.loadUrl(paramString);
		webView.setWebChromeClient(new WebChromeClient() {
			public void onProgressChanged(WebView paramWebView, int paramInt) {
				int byte0;
				if (paramInt == 100) {
					byte0 = 8;
				} else {
					byte0 = 0;
				}
				mProgressBar.setVisibility(byte0);
				mProgressBar.setProgress(paramInt);
				super.onProgressChanged(paramWebView, paramInt);
			}
		});
	}

	public void onClick(View paramView) {

	}

	class WebViewC extends WebViewClient {

		WebViewC() {
		}

		public void onPageFinished(WebView paramWebView, String paramString) {
			super.onPageFinished(paramWebView, paramString);
		}

		public void onPageStarted(WebView paramWebView, String webURL,
				Bitmap paramBitmap) {
			if (webURL.indexOf("access_token=") > 0) {
				getAccessToken(paramWebView, webURL);
				return;
			}
			super.onPageStarted(paramWebView, webURL, paramBitmap);
		}

		/*
		 * TODO Android2.2及以上版本才能使用该方法
		 * 目前https://open.t.qq.com中存在http资源会引起sslerror，待网站修正后可去掉该方法
		 */
		public void onReceivedSslError(WebView view, SslErrorHandler handler,
				SslError error) {
			if ((null != view.getUrl())
					&& (view.getUrl().startsWith("https://open.t.qq.com"))) {
				handler.proceed();// 接受证书
			} else {
				handler.cancel(); // 默认的处理方式，WebView变成空白页
			}
			// handleMessage(Message msg); 其他处理
		}

		public boolean shouldOverrideUrlLoading(WebView paramWebView,
				String webURL) {
			paramWebView.loadUrl(webURL);
			return true;
		}
	}

	private void getAccessToken(WebView paramWebView, String redirectUrl) {
		// https://api.weibo.com/oauth2/default.html#access_token=2.00283JBDYb9XND6c3f9590ccvtTJuB
		// &remind_in=126141&expires_in=126141&uid=2765406047
		String access_token = "";
		int accessIndex = redirectUrl.indexOf("access_token=");
		if (ShareConfig.SHARE_WEIBO_QQ.equals(weiboType)) {
			String responseData = redirectUrl.substring(accessIndex);
			OAuthV2Client.parseAccessTokenAndOpenId(responseData, oAuth);
			Intent intent = new Intent();
			intent.putExtra("oauth", oAuth);
			setResult(RESULT_CODE, intent);
			paramWebView.destroyDrawingCache();
			paramWebView.destroy();
			// 存储AccessToken到本地
			OAuth oauth = new OAuth();
			oauth.setAccessToken(oAuth.getAccessToken());
			oauth.setResponseData(responseData);
			oauth.setWeiboType(weiboType);
			TokenStore.storeOAuth(WeiboOAuthActivity.this, oauth);
			finish();
		} else if (ShareConfig.SHARE_WEIBO_SINA.equals(weiboType)) {
			int remindIndex = redirectUrl.indexOf("remind_in");
			int userIndex = redirectUrl.indexOf("uid");
			access_token = redirectUrl.substring(accessIndex + 13,
					remindIndex - 1);
			userWBId = redirectUrl.substring(userIndex + 4);
			// 存储AccessToken到本地
			OAuth oauth = new OAuth();
			oauth.setAccessToken(access_token);
			oauth.setWeiboType(weiboType);
			boolean result = TokenStore.storeOAuth(WeiboOAuthActivity.this,
					oauth);
			// 关闭当前
			WeiboOAuthActivity.this.finish();
			if (result) {
				showShortToast(WeiboOAuthActivity.this, "授权成功");
				// 获取用户信息并存储
				getSinaUserInfo();
			} else {
				showShortToast(WeiboOAuthActivity.this, "授权失败");
			}
		}
	}

	/**
	 * 获取新浪用户信息
	 */
	private void getSinaUserInfo() {
		AsyncLoadData ald = new AsyncLoadData(this, new AsyncAction() {

			@Override
			public void doLoad() throws Exception {
				Utility.setAuthorization(new Oauth2AccessTokenHeader());
				OAuth oauth = TokenStore.fetchOAuth(WeiboOAuthActivity.this,
						ShareConfig.SHARE_WEIBO_SINA);
				String accessToken = oauth.getAccessToken();
				WeiboParameters params = new WeiboParameters();
				params.add("uid", userWBId);
				params.add("access_token", accessToken);
				AccessToken at = new AccessToken(ShareConfig.SINA_App_Key,
						ShareConfig.SINA_App_Seret);
				Weibo weibo = Weibo.getInstance();
				weibo.setAccessToken(at);
				Token tk = weibo.getAccessToken();
				tk.setToken(accessToken);
				String rlt = Utility.openUrl(WeiboOAuthActivity.this,
						ShareConfig.sina_users_show, Utility.HTTPMETHOD_GET,
						params, tk);
				if (!StringUtil.isNullOrEmpty(rlt)) {
					System.out.println(rlt);
					// 解析用户信息JSON数据
					WeiBoUserEntity wue = new ShareParseJson()
							.parseSinaUserJson(rlt);
					// 将用户信息存于配置文件
					TokenStore.storeUserInfo(WeiboOAuthActivity.this, wue,
							ShareConfig.SHARE_WEIBO_SINA);
				}
			}

		});
		ald.execute(0);
	}

}